
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

var route_steps     = [];
var endMarker      = [];
var startMarker    = [];
var route_lines     = [];
var directions_routes   = [];

 HHJsLib.register({
     init: function() {
        var self    = this;
        this.initMapHeight();
        this.initMap();
        this.bindSearchFormSubmit();
        this.initDirectionsService();
        $(window).resize(function() {
            self.initMapHeight();
        });
        this.bindAutoSyncStuffGPSInfo();
     },
     infoWindow: null,
     bindAutoSyncStuffGPSInfo: function() {
        var self    = this;
        setInterval(function() {
            self.doSearching($('#search-form').serialize());
        }, 5000);
     },
     isSearching: false,
     bindSearchFormSubmit: function() {
        var self    = this;
        $('#search-form').submit(function() {
            $('#loading-modal').modal('show');
            self.doSearching($(this).serialize());
            return false;
        });
     },
     doSearching: function(data) {
        var self    = this;
        if(self.isSearching) {
            return;
        }
        $.getJSON(
            queryUrl + 'admin/map/astuffsearch',
            data,
            function(response) {
                self.isSearching    = false;
                $('#loading-modal').modal('hide');
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.reSetStuffOnMap(response.data.staffList);
                //self.reSetOrderOnMap(response.data.orderList);
            }
        );
     },
     orderMarkerMap: {},
     goodsLabelList: {},
     orderStatusList: {},
     reSetOrderOnMap: function(list) {
        var idsStr          = '';
        for (var ele in list) {
            var order       = list[ele];
            idsStr          += ',' + order.id;
            if(typeof(order.address.latitude) !== 'undefined') {
                order.address['loc']    = order.address.latitude + ',' + order.address.longitude;
            }
            if(!order.address.loc || 0 > order.address.loc.indexOf(',')) {
                continue;
            }
            if('undefined' !== typeof(this.orderMarkerMap['user_' + order.id])) {
                if(!this.orderMarkerMap['order_' + order.id].getMap()) {
                    this.orderMarkerMap['order_' + order.id].setMap(this.map);
                    this.goodsLabelList['order_label_' + order.id].setMap(this.map);
                }
                var pos         = order.address.loc.split(',');
                var LatLng      = new qq.maps.LatLng(pos[0], pos[1]);
                var position    = this.orderMarkerMap['order_' + order.id].getPosition();
                if(order.status != this.orderStatusList['order_status' + order.id]) {
                    this.orderMarkerMap['order_' + order.id].setIcon(this.getOrderMarkerIcon(order.status));
                    this.goodsLabelList['order_label_' + order.id].setStyle(this.labelStyle['status' + order.status]);
                    this.orderStatusList['order_status' + order.id] = order.status;
                }
                if(position.lat == LatLng.lat && position.lng == LatLng.lng) {
                    continue;
                }
                this.orderMarkerMap['order_' + order.id].setPosition(LatLng);
                this.goodsLabelList['order_label_' + order.id].setPosition(LatLng);
                continue;
            }
            this.setOrderMarkerToMap(order);
        }
        idsStr += ',';
        for(var ele in this.orderMarkerMap) {
            var oid     = ele.split('_');
            if(0 <= idsStr.indexOf(',' + oid[1] + ',')) {
                continue;
            }
            this.orderMarkerMap['order_' + oid[1]].setMap(null);
            this.goodsLabelList['order_label_' + oid[1]].setMap(null);
        }
     },
     setOrderMarkerToMap: function(order) {
        var self        = this;
        var pos         = order.address.loc.split(',');
        var LatLng      = new qq.maps.LatLng(pos[0], pos[1]),
            size        = new qq.maps.Size(32, 32);
        var marker      = new qq.maps.Marker({
            icon: this.getOrderMarkerIcon(order.status),
            map: this.map,
            title: (order.name + '-' + order.id),
            position: LatLng
        });
        var status      = order.status > 2 ? 2 : order.status;
        this.orderMarkerMap['order_' + order.id]     = marker;
        var label = new qq.maps.Label({
            offset: new qq.maps.Size(-(order.name.length / 2 * 6.8), -58),
            position: LatLng,
            style: this.labelStyle['status' + status],
            content: order.name
        });
        label.setMap(this.map);
        this.goodsLabelList['order_label_' + order.id]    = label;
        this.orderStatusList['order_status' + order.id]   = order.status;
        if(orderList && orderList.length == 1) {
            marker.setAnimation(qq.maps.Animation.BOUNCE);
        }
        //获取标记的点击事件
        qq.maps.event.addListener(marker, 'click', function() {
            self.showOrderInfo(this);
        });
     },
     showOrderInfo: function(marker) {
        var title   = marker.getTitle();
        var info    = title.split('-');
        var self    = this;
        var opts = {
            width : 250,     // 信息窗口宽度
            enableMessage:true//设置允许信息窗发送短息
        };
        $.getJSON(
            queryUrl + 'admin/order/ainfo',
            {id: info[1]}, 
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.setOrderInfoWindow(response.data, marker);
            }
        );
     },
     reSetStuffOnMap: function(list) {
        var totalOnline     = 0;
        var totalOffline    = 0;
        var idsStr          = '';
        for (var ele in list) {
            var stuff   = list[ele];
            idsStr          += ',' + stuff.id;
            if(1 == stuff.status) {
                totalOffline ++;
            } else {
                totalOnline ++;
            }
            if(!stuff.position || 0 > stuff.position.indexOf(',')) {
                continue;
            }
            if('undefined' !== typeof(this.markerList['user_' + stuff.id])) {
                if(!this.markerList['user_' + stuff.id].getMap()) {
                    this.markerList['user_' + stuff.id].setMap(this.map);
                    this.labelList['user_label_' + stuff.id].setMap(this.map);
                }
                var pos         = stuff.position.split(',');
                var LatLng      = new qq.maps.LatLng(pos[0], pos[1]);
                var position    = this.markerList['user_' + stuff.id].getPosition();
                if(stuff.status != this.statusList['user_status' + stuff.id]) {
                    this.markerList['user_' + stuff.id].setIcon(this.getMarkerIcon(stuff.image_path, stuff.status));
                    this.labelList['user_label_' + stuff.id].setStyle(this.labelStyle['status' + stuff.status]);
                    this.statusList['user_status' + stuff.id] = stuff.status;
                }
                if(position.lat == LatLng.lat && position.lng == LatLng.lng) {
                    continue;
                }
                this.markerList['user_' + stuff.id].setPosition(LatLng);
                this.labelList['user_label_' + stuff.id].setPosition(LatLng);
                continue;
            }
            this.setMarkerToMap(stuff);
        }
        idsStr += ',';
        for(var ele in this.markerList) {
            var uid     = ele.split('_');
            if(0 <= idsStr.indexOf(',' + uid[1] + ',')) {
                continue;
            }
            this.markerList['user_' + uid[1]].setMap(null);
            this.labelList['user_label_' + uid[1]].setMap(null);
        }
        $('#total-online').html(totalOnline);
        $('#total-offline').html(totalOffline);
     },
     map: null,
     initMap: function() {
        var self    = this;
        setTimeout(function() {
            //定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
            self.map = new qq.maps.Map(document.getElementById("container"), {
                center: new qq.maps.LatLng(27.57771, 110.04098),
                zoom: 13,                 // 地图的中心地理坐标。
                draggable: true,          //设置是否可以拖拽
                panControl: true,         //平移控件的初始启用/停用状态。      
                zoomControl: true,       //缩放控件的初始启用/停用状态。
                scaleControl: true        //滚动控件的初始启用/停用状态。
            });
            self.doSearching($('#search-form').serialize());
        }, 1000);
     },
     labelStyle: {
        'status1': {fontSize: '12px', color: '#fff', borderColor: '#999', background: '#999', padding: '2px 4px', borderRadius: '5px'},
        'status2': {fontSize: '12px', color: '#fff', background: '#f30', padding: '2px 4px', borderRadius: '5px'}
     },
     statusList: {},
     markerList: {},
     labelList: {},
     setStuffOnMap: function() {
        var  self   = this;
        this.markerList = [];
        for (var ele in stuffList) {
            var stuff   = stuffList[ele];
            if(!stuff.position || 0 > stuff.position.indexOf(',')) {
                continue;
            }
            this.setMarkerToMap(stuff);
        }
     },
     touri: function(uri) {
        if( 0 <= uri.indexOf('http')) {
            return uri;
        }

        return siteUrl + uri;
     },
     getOrderMarkerIcon: function(status) {
        var avatar      = siteUri + "images/icon-package-" + status + "-32.png";
        size            = new qq.maps.Size(32, 32);

        return new qq.maps.MarkerImage(avatar, size);
     },
     getMarkerIcon: function(avatar, status) {
        var avatar      = typeof(avatar) === 'undefined' || !avatar 
            ? siteUri + "images/status-" + status + "-32.png" : this.touri(avatar);
        avatar          = siteUri + "images/status-" + status + "-32.png";
        size            = new qq.maps.Size(32, 32);

        return new qq.maps.MarkerImage(avatar, size);
     },
     setMarkerToMap: function(stuff) {
        var self        = this;
        var pos         = stuff.position.split(',');
        var LatLng      = new qq.maps.LatLng(pos[0], pos[1]),
            size        = new qq.maps.Size(32, 32);
        var marker      = new qq.maps.Marker({
            icon: this.getMarkerIcon(stuff.image_path, stuff.status),
            map: this.map,
            title: (stuff.true_name + '-' + stuff.id),
            position: LatLng
        });
        this.markerList['user_' + stuff.id]     = marker;
        var label = new qq.maps.Label({
            offset: new qq.maps.Size(-(stuff.true_name.length / 2 * 6.8), -58),
            position: LatLng,
            style: this.labelStyle['status' + stuff.status],
            content: stuff.true_name
        });
        label.setMap(this.map);
        this.labelList['user_label_' + stuff.id]    = label;
        this.statusList['user_status' + stuff.id]   = stuff.status;
        if(stuffList && stuffList.length == 1) {
            marker.setAnimation(qq.maps.Animation.BOUNCE);
        }
        //获取标记的点击事件
        qq.maps.event.addListener(marker, 'click', function() {
            self.showStuffInfo(this);
        });
        //获取标记的点击事件
        qq.maps.event.addListener(marker, 'mouseover', function() {
            self.showStuffTaskInfo(this);
        });
     },
     showStuffTaskInfo: function(marker) {
        var title   = marker.getTitle();
        var info    = title.split('-');
        var self    = this;
        $.getJSON(
            queryUrl + 'admin/userpeisongyuan/ainfo',
            {id: info[1]}, 
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.setUserTaskListLines(response.data.tasks, marker);
            }
        );
     },
     showStuffInfo: function(marker) {
        var title   = marker.getTitle();
        var info    = title.split('-');
        var self    = this;
        var opts = {
            width : 250,     // 信息窗口宽度
            enableMessage:true//设置允许信息窗发送短息
        };
        $.getJSON(
            queryUrl + 'admin/userpeisongyuan/ainfo',
            {id: info[1]}, 
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.setUserInfoWindow(response.data.info, marker, response.data.tasks.length);
            }
        );
     },
     directionsService: null,
     lineColorList: [
         '#3893F9', '#38F3F9', '#4FFD39', '#D7FF39', '#FFF939', '#3E30D7', 
         '#FFD139', '#FFA939', '#FF7B39', '#F83842', '#DE32A8', '#9330D7'
     ],
     initDirectionsService: function() {
        var self            = this;
        this.directionsService = new qq.maps.DrivingService({
            complete : function(response){
                self.taskLoc ++;
                var start = response.detail.start,
                    end = response.detail.end;
                
                var anchor = new qq.maps.Point(6, 6),
                    size = new qq.maps.Size(24, 36),
                    start_icon = new qq.maps.MarkerImage(
                        siteUri + 'images/busmarker.png', 
                        size, 
                        new qq.maps.Point(0, 0),
                        anchor
                    ),
                    end_icon = new qq.maps.MarkerImage(
                        siteUri + 'images/busmarker.png', 
                        size, 
                        new qq.maps.Point(24, 0),
                        anchor
                    );
                startMarker.push(new qq.maps.Marker({
                      icon: start_icon,
                      position: start.latLng,
                      map: self.map,
                      zIndex: self.taskLoc + 1
                }));
                endMarker.push(new qq.maps.Marker({
                      icon: end_icon,
                      position: end.latLng,
                      map: self.map,
                      zIndex: self.taskLoc + 1
                }));
                var directions_routes = response.detail.routes;
               //所有可选路线方案
               for(var i = 0;i < directions_routes.length; i++){
                    var route = directions_routes[i],
                        legs = route; 
                    //调整地图窗口显示所有路线    
                    self.map.fitBounds(response.detail.bounds); 
                    //所有路程信息            
                    //for(var j = 0 ; j < legs.length; j++){
                        var steps = legs.steps;
                        route_steps = steps;
                        polyline = new qq.maps.Polyline(
                            {
                                path: route.path,
                                strokeColor: self.lineColorList.length < (self.taskLoc + 1) ? 0 : self.lineColorList[self.taskLoc],
                                strokeWeight: 6,
                                map: self.map
                            }
                        )  
                        route_lines.push(polyline);
                    //}
               }
               //继续画线
               self.searchTaskLines();
            },
            error: function(data) {
               console.log(data);
               self.taskLoc ++;
               self.searchTaskLines();
               if(data !== 'UNKNOWN_ERROR') {
                    alert(data);
               }
            },
            map: this.map
        });
     },
     setUserTaskListLines: function(tasks, marker) {
        this.taskLoc = 0;
        HHJsLib.info('正在绘制配送员任务路线中，请稍等...');
        this.cleanLines(route_lines);
        this.cleanLines(startMarker);
        this.cleanLines(endMarker);
        this.directionsService.setLocation("怀化");
        this.directionsService.setPolicy(qq.maps.DrivingPolicy['LEAST_TIME']);
        this.curTaskList = tasks;
        //this.searchTaskLines();
        this.drawTaskLines(marker);
     },
     drawTaskLines: function(marker) {
        var self    = this;
        var len     = this.lineColorList.length;
        var anchor  = new qq.maps.Point(6, 6),
            size    = new qq.maps.Size(24, 36),
            start_icon = new qq.maps.MarkerImage(
                siteUri + 'images/busmarker.png', 
                size, 
                new qq.maps.Point(0, 0),
                anchor
            ),
            end_icon = new qq.maps.MarkerImage(
                siteUri + 'images/busmarker.png', 
                size, 
                new qq.maps.Point(24, 0),
                anchor
            );
        for(var ele in self.curTaskList) {
            var task    = self.curTaskList[ele];
            var color   = this.lineColorList[ele];
            var startPosition   = new qq.maps.LatLng(task.buy_address.latitude, task.buy_address.longitude);
            //添加折线覆盖物
            var polyline = new qq.maps.Polyline({
                path: [
                    marker.getPosition(), 
                    startPosition
                ],
                strokeColor: color,
                strokeWeight: 4,
                editable:false,
                map: this.map
            });
            var tmpMarker  = new qq.maps.Marker({
                title: (task.name + '-' + task.id),
                icon: start_icon,
                position: startPosition,
                map: self.map,
                zIndex: self.taskLoc + 1
            });
            startMarker.push(tmpMarker);
            route_lines.push(polyline);
            //获取标记的点击事件
            qq.maps.event.addListener(tmpMarker, 'click', function() {
                self.showOrderInfo(this);
            });
            var endPosition = new qq.maps.LatLng(task.address.latitude, task.address.longitude);
            var polyline    = new qq.maps.Polyline({
                path: [
                    marker.getPosition(), 
                    endPosition
                ],
                strokeColor: color,
                strokeWeight: 4,
                editable:false,
                map: this.map
            });
            tmpMarker  = new qq.maps.Marker({
                title: (task.name + '-' + task.id),
                icon: end_icon,
                position: endPosition,
                map: self.map,
                zIndex: self.taskLoc + 1
            });
            endMarker.push(tmpMarker);
            route_lines.push(polyline);
            qq.maps.event.addListener(tmpMarker, 'click', function() {
                self.showOrderInfo(this);
            });
        }
     },
     cleanLines: function(overlays) {
        var overlay;
        while(overlay = overlays.pop()){
            overlay.setMap(null);
        }
     },
     curTaskList: [],
     taskLoc: 0,
     searchTaskLines: function() {
        var self    = this;
        setTimeout(function() {
            if(self.taskLoc >= self.curTaskList.length) {
                HHJsLib.succeed('绘制完成！');
                return;
            }
            var task    = self.curTaskList[self.taskLoc];
            self.directionsService.search(
                new qq.maps.LatLng(task.buy_address.latitude, task.buy_address.longitude), 
                new qq.maps.LatLng(task.address.latitude, task.address.longitude)
            );
        }, 500);
     },
     setOrderInfoWindow: function(orderInfo, marker) {
        var self        = this;
        var tpl         = $('#order-info-tpl').html();
        var sContent    = tpl.replace(/{name}/ig, orderInfo.name)
        .replace(/{stuff}/ig, orderInfo.peisongyuan_id)
        .replace(/{peisong_time}/ig, orderInfo.peisong_time)
        .replace(/{id}/ig, orderInfo.id)
        .replace(/{shop_time}/ig, orderInfo.shop_time)
        .replace(/{get_goods_time}/ig, orderInfo.get_goods_time)
        .replace(/{address}/ig, orderInfo.address.detail)
        .replace(/{done_time}/ig, orderInfo.done_time)
        .replace(/{status}/ig, orderInfo.status);
        //添加到提示窗
        this.infoWindow     = new qq.maps.InfoWindow({
            map: this.map
        });
        this.infoWindow.open(); 
        this.infoWindow.setContent(sContent);
        this.infoWindow.setPosition(marker.getPosition());
     },
     setUserInfoWindow: function(userInfo, marker, tasks) {
        var self        = this;
        var tpl         = $('#stuff-info-tpl').html();
        var sContent    = tpl.replace(/{name}/ig, userInfo.name)
        .replace(/{phone}/ig, userInfo.phone)
        .replace(/{tasks}/ig, tasks)
        .replace(/{id}/ig, userInfo.id)
        .replace(/{loginTime}/ig, userInfo.loginTime)
        .replace(/{status}/ig, userInfo.status)
        .replace(/{address}/ig, userInfo.address)
        .replace(/{verify}/ig, userInfo.verify)
        .replace(/{src}/ig, userInfo.avatar);
        //添加到提示窗
        this.infoWindow     = new qq.maps.InfoWindow({
            map: this.map
        });
        this.infoWindow.open(); 
        this.infoWindow.setContent(sContent);
        this.infoWindow.setPosition(marker.getPosition());
        setTimeout(function() {
            //图片加载完毕重绘infowindow
            document.getElementById('stuff-avatar').onload = function (){
                self.infoWindow.redraw();   //防止在网速较慢，图片未加载时，生成的信息框高度比图片的总高度小，导致图片部分被隐藏
            };
        }, 1000);
     },
     initMapHeight: function() {
        var height  = $(document).height() - 88 - 200;
        $('#container').css('height', height);
     }
 });
